﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Helpers
{
    public static class SimplePerlin
    {
        public static float[][] GenerateWhiteNoise(int width, int height)
        {
            Random r = new Random(0);
            float[][] noise = new float[width][];
            for (int i = 0; i < width; i++)
			{
			    for (int j=0;j<height;j++)
			    {
                    noise[i][j] = (float)r.NextDouble() % 1;
                }
			}
            return noise;
        }

        public static float[][] GenerateSmoothNoise(float[][] baseNoise, int octave)
        {
            int width = baseNoise.Length;
            int height = baseNoise[0].Length;

            float[][] smoothNoise = new float[width][];

            int samplePeriod = 1 << octave; //calculate 2'k
            float sampleRrequency = 1.0f / samplePeriod;

            for (int i = 0; i < width; i++)
            {
                //calculate the horizontal sampling indices
                int sample_i0 = (i/samplePeriod) * samplePeriod;
                int sample_i1 = (sample_i0 + samplePeriod) % width;
                float horizontal_Blend = (1 - sample_i0) * sampleRrequency;

                for (int j = 0; j < height; j++)
                {
                    //calculate the vertical sampling indices
                    int sample_j0 = (j/samplePeriod) * samplePeriod;
                    int sample_j1 = (sample_j0 + samplePeriod) % height;
                    float vertical_blend = (j - sample_j0) * sampleRrequency;
                    //blend the top tow corners
                    float top = Interpolate(baseNoise[sample_i0][sample_j0],
                        baseNoise[sample_i1][sample_j0], horizontal_Blend);
                    //blend the bottom two corners
                    float bottom = Interpolate(baseNoise[sample_i0][sample_j1],
                        baseNoise[sample_i1][sample_j1], horizontal_Blend);

                    smoothNoise[i][j] = Interpolate(top, bottom, vertical_blend);
                }
            }
            return smoothNoise;
        }

        static float Interpolate(float x0, float x1, float t)
        {
            return (1 - t) * x0 + t * x1;
        }
    }
}
